package com.net.framework.help.httprequest;

import android.provider.Settings;

import com.net.framework.help.BuildConfig;
import com.net.framework.help.application.BaseApplication;
import com.net.framework.help.utils.LogUtils;
import com.net.framework.help.utils.PackageInfoUtil;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Author：xiaobin.zhang
 * Email：154722566@qq.com
 * Date：2016/6/30 11:05
 * Desc：<--功能描述-->HTTP
 */
public class OkHttp3Utils {
    public static String userToken = "";//用户的token
    private static OkHttpClient mOkHttpClient;
    //设置缓存目录
    private static File cacheDirectory = new File(BaseApplication.getApplication().getCacheDir().getAbsolutePath(), "FrameworkCache");
    private static Cache cache = new Cache(cacheDirectory, 10 * 1024 * 1024);

    /**
     * 获取OkHttpClient对象
     *
     * @return
     */
    public static OkHttpClient getOkHttpClient() {
        //打印日志拦截器
        if (null == mOkHttpClient) {
            mOkHttpClient = new OkHttpClient.Builder()
//                    .cookieJar(new CookiesManager())
                    //加入缓存策略拦截器
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request request = chain.request().newBuilder()
                                    .addHeader("version", PackageInfoUtil.getPackageInfo(BaseApplication.getApplication()).versionName)//应用版本
                                    .addHeader("versionCode", PackageInfoUtil.getPackageInfo(BaseApplication.getApplication()).versionCode + "")//应用版本Code
                                    .addHeader("source", "2")//设备类型 1小程序，2安卓 3ios  4wap
                                    .addHeader("phoneId", getInfoIMEI())//手机唯一标识码
                                    .addHeader("phoneModel", android.os.Build.BRAND + " " + android.os.Build.MODEL)//手机型号
                                    .addHeader("systemVersion", android.os.Build.VERSION.RELEASE)//系统版本
                                    .addHeader("Author", userToken)
                                    .build();
                            LogUtils.println("Header数据====" + request.headers().toString());
                            return chain.proceed(request);
                        }
                    })
                    //设置日志打印拦截器
                    //NONE 不输出日志
                    //BASIC 只输出请求方式响应码等基本信息
                    //HEADERS 只输出请求和响应的头部信息
                    //BODY 输出请求和响应的头部和请求体信息
                    .addInterceptor(new HttpLoggingInterceptor().setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BASIC : HttpLoggingInterceptor.Level.NONE))
                    //设置请求超时时间
                    .connectTimeout(1, TimeUnit.MINUTES)
                    //设置写入超时时间
                    .writeTimeout(1, TimeUnit.MINUTES)
                    //设置读取超时时间
                    .readTimeout(1, TimeUnit.MINUTES)
                    //设置缓存位置、空间大小
                    .cache(cache).build();
        }
        return mOkHttpClient;
    }

    //    /**
    //     * 拦截器
    //     */
    //    private class MyIntercepter implements Interceptor {
    //        @Override
    //        public Response intercept(Chain chain) throws IOException {
    //            Request request = chain.request();
    //            request.newBuilder()
    //                    .addHeader("appVersion", PackageInfoUtil.getPackageInfo(BaseApplication.getApplication()).versionName)//应用版本
    //                    .addHeader("handleType", "Android")//设备类型
    //                    .addHeader("phoneId", getInfo().getDeviceId())//手机唯一标识码
    //                    .addHeader("phoneModel", android.os.Build.BRAND + " " + android.os.Build.MODEL)//手机型号
    //                    .addHeader("systemVersion", android.os.Build.VERSION.RELEASE)//系统版本
    //                    .build();
    //            return chain.proceed(request);
    //        }
    //    }


//    /**
//     * 自动管理Cookies
//     */
//    private static class CookiesManager implements CookieJar {
//        private final PersistentCookieStore cookieStore = new PersistentCookieStore(BaseApplication.getApplication());
//
//        @Override
//        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
//            if (cookies != null && cookies.size() > 0) {
//                for (Cookie item : cookies) {
//                    cookieStore.add(url, item);
//                    LogUtils.println("接口》》》" + url);
//                }
//            }
//        }
//
//        @Override
//        public List<Cookie> loadForRequest(HttpUrl url) {
//            List<Cookie> cookies = cookieStore.get(url);
//            LogUtils.println("接口》》》" + url);
//            return cookies;
//        }
//    }


    /***
     * 获取手机基本信息
     */
    private static String getInfoIMEI() {
        String ANDROID_ID = Settings.System.getString(BaseApplication.getApplication().getContentResolver(), Settings.System.ANDROID_ID);
        return ANDROID_ID;
    }
}
